<template>
  <div style="height:100%;">
    <!-- 搜索框区域 -->
    <div style="height:6%;">
      <el-form
        :inline="true"
        :model="ruleForm"
        size='mini'
      >
        <el-form-item
          label="设备号"
          prop="devId"
        >
          <el-input
            v-model.trim="ruleForm.devId"
            placeholder="请填写设备号"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="onSearch"
            ></el-button>
          </el-input>
        </el-form-item>

        <el-form-item
          label="机车号"
          prop="devId"
        >
          <el-input
            v-model.trim="ruleForm.en"
            placeholder="请填写机车号"
            clearable
          >

          </el-input>
        </el-form-item>

        <el-form-item
          label="车次号"
          prop="tn"
        >
          <el-input
            v-model.trim="ruleForm.tn"
            placeholder="请填写车次号"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="showList"
            :loading="btnLoading"
          >查询</el-button>
        </el-form-item>
        <el-form-item v-if="track.flag">
          <el-divider
            direction="vertical"
            style="height: 100%;"
          ></el-divider>
          <span style="color:red;">有且仅有一个设备，正在实时规划轨迹！</span>
        </el-form-item>

      </el-form>

      <DevDialogList
        ref="devDialogList"
        @confirm="confirm"
      />
    </div>
    <!-- 百度地图示例 -->
    <baidu-map
      class="bm-view"
      :center="center"
      :zoom="zoom"
      :min-zoom='minZoom'
      :max-zoom='maxZoom'
      :scroll-wheel-zoom="true"
      @ready="map_handler"
      map-type="BMAP_NORMAL_MAP"
    >
      <!-- 地图类型,不能用，一旦弹出信息窗体就报错！！！！！！ -->
      <!-- <bm-map-type
        :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP','BMAP_SATELLITE_MAP']"
        anchor="BMAP_ANCHOR_TOP_RIGHT"
      ></bm-map-type> -->
      <!-- 比例尺 -->
      <bm-scale anchor="BMAP_ANCHOR_BUTTOM_LEFT"></bm-scale>
      <!-- 缩放 -->
      <bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation>
      <!-- 轨迹图 -->
      <bm-polyline
        v-if="track.flag"
        :path="track.lineArr"
        stroke-color="blue"
        :stroke-opacity="0.5"
        :stroke-weight="2"
        :editing="false"
      ></bm-polyline>
      <!-- 描点 -->
      <bml-marker-clusterer :averageCenter="true">
        <bm-marker
          v-for="item in devList"
          :key="item.devId"
          :position="{lng: item.longitude, lat: item.latitude}"
          :dragging="false"
          @click="infoWindowOpen(item)"
          :icon="item.onlineState?trainOnlineIcon:trainOfflineIcon"
        >
          <bm-label
            :content="item.en"
            :labelStyle="labelStyle"
            :offset="{width: -10, height: 30}"
          />
        </bm-marker>
      </bml-marker-clusterer>

      <!-- 弹框不能放在循环体里面 -->
      <bm-info-window
        :position="{lng: infoWindow.longitude, lat: infoWindow.latitude}"
        :show="showInfo"
        @close="infoWindowClose()"
        :offset="{width: 5, height: 15}"
      >
        <p><b>设备号：</b>{{infoWindow.devId}}</p>
        <p><b>机车号：</b>{{infoWindow.en}}</p>
        <p><b>线路名称：</b>{{infoWindow.lineName}}</p>
        <p><b>gps时间：</b>{{infoWindow.gpsTime}}</p>
        <p v-if="infoWindow.onlineState"><b>在线状态：</b><span style="color:green">在线</span></p>
        <p v-else><b>在线状态：</b><span style="color:red">离线</span></p>
      </bm-info-window>

    </baidu-map>
  </div>

</template>

<script>
import { BmlMarkerClusterer } from 'vue-baidu-map-v3';
import { getAction } from '@/api/manage';
import DevDialogList from '../dev/DevDialogList.vue';
export default {
  components: {
    BmlMarkerClusterer,
    DevDialogList,
  },
  data() {
    return {
      //搜索相关参数
      ruleForm: {
        devId: '',
        en: '',
      },
      showSearch: false,
      btnLoading: false,
      //定时任务
      timer: undefined,
      //列表
      devList: [],
      //地图相关参数
      center: { lng: 116.404, lat: 39.915 },
      zoom: 5,
      minZoom: 5,
      maxZoom: 19,
      showInfo: false,
      infoWindow: {},
      trainOnlineIcon: {
        //火车在线
        url: require('@/assets/train-green.png'),
        size: {
          width: 25,
          height: 30,
        },
        opts: {
          anchor: {
            //偏移量
            width: 0,
            height: 0,
          },
          imageSize: {
            width: 25,
            height: 30,
          },
        },
      },
      trainOfflineIcon: {
        //火车在线
        url: require('@/assets/train-solid.png'),
        size: {
          width: 25,
          height: 30,
        },
        opts: {
          anchor: {
            //偏移量
            width: 0,
            height: 0,
          },
          imageSize: {
            width: 25,
            height: 30,
          },
        },
      },
      labelStyle: {
        color: '#fff',
        'background-color': 'rgba(0, 0, 0, 0.5)',
        'border-radius': '10px',
        padding: '0 10px',
        'font-size': '14px',
        'line-height': '20px',
        border: '0',
      },
      //轨迹（当前设备有且仅有一个才会显示轨迹）
      track: {
        flag: false, //当前列表是否只有一个
        devId: '', //当前设备id
        lineArr: [], //轨迹数组
      },
    };
  },
  mounted() {
    this.$nextTick(() => {
      console.log('开启定时任务');
      this.showList();
      this.timer = setInterval(() => {
        this.showList();
      }, 1000 * 3);
    });
  },
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
      console.log('关闭定时任务');
    }
  },
  methods: {
    /**
     * 地图加载完成调用函数
     */
    map_handler({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
      //添加地图类型控件【地图/卫星】
      this.map.addControl(
        new BMap.MapTypeControl({
          mapTypes: [BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP, BMAP_HYBRID_MAP],
        })
      );
      //添加监听事件，监听地图层级变化
      this.map.addEventListener('zoomend', (e) => {
        let isErrorZoom = this.map.getZoom() > this.maxZoom;
        let msg = '地图级别: ' + this.map.getZoom();
        if (isErrorZoom) {
          msg += ', 当前地图中只有' + this.maxZoom + '级地图,超过的无法显示!';
          this.$notify({
            message: msg,
            position: 'bottom-right',
            type: 'warning',
          });
          return;
        }
        this.$notify({
          message: msg,
          position: 'bottom-right',
        });
      });
    },
    /**
     * 查询设备列表
     */
    onSearch() {
      this.$refs.devDialogList.show('map');
    },
    /**
     * 选择设备回调函数
     */
    confirm(obj) {
      this.ruleForm.devId = obj.devId;
      this.ruleForm.en = obj.en;
    },
    /**
     * 搜索设备列表接口
     */
    showList() {
      this.btnLoading = true;
      getAction('/device/queryDevBasicStateList', {
        devId: this.ruleForm.devId,
        en: this.ruleForm.en,
        tn: this.ruleForm.tn,
      })
        .then((res) => {
          if (res.code == 200) {
            this.devList = res.data;
            console.log('devList', this.devList);
            //判断是否需要填入轨迹
            this.handleTrack(this.devList);
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        })
        .finally(() => {
          this.btnLoading = false;
        });
    },
    /**
     * 根据查询返回的数据处理轨迹
     * ==只有返回设备列表有且仅有一条时，才会填入轨迹
     * @param {*} devList 查询返回设备列表
     */
    handleTrack(devList) {
      if (!devList || devList.length == 0 || devList.length > 1) {
        this.track.flag = false;
        return;
      }
      const element = devList[0];
      let devId = element.devId;
      if (devId != this.track.devId) {
        //之前不是本设备的轨迹，清空并重新填入
        this.track.lineArr = [];
      }
      this.track.devId = devId;
      this.track.flag = true;
      this.track.lineArr.push({
        lng: element.longitude,
        lat: element.latitude,
      });
      console.log('this.track', this.track);
    },
    /**
     * 展示描点信息
     */
    infoWindowOpen(marker) {
      this.showInfo = true;
      this.infoWindow.devId = marker.devId;
      this.infoWindow.en = marker.lineName;
      this.infoWindow.gpsTime = marker.gpsTime;
      this.infoWindow.onlineState = marker.onlineState;
      this.infoWindow.longitude = marker.longitude;
      this.infoWindow.latitude = marker.latitude;
    },
    /**
     * 关闭描点信息
     */
    infoWindowClose(marker) {
      this.showInfo = false;
    },
  },
};
</script>

<style scoped>
.bm-view {
  width: 100%;
  height: 94%;
}
/* .labelStyle {
  color: '#fff';
  background-color: 'rgba(0, 0, 0, 0.5)';
  border-radius: '10px';
  padding: '0 10px';
  font-size: '14px';
  line-height: '20px';
  border: '0';
  transform: 'translateX(-50%)';
} */
</style>